package com.pay.omni;

import com.alibaba.fastjson.JSON;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.validation.constraints.NotNull;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/***
 * @author abc
 * @desc RpcHttpUtil
 * @date  2019/7/2 0002 上午 11:29
 */
@Slf4j
public class RpcHttpUtil {

    private String URL;
    private JsonRpcHttpClient mClient;

    public RpcHttpUtil(String rpc_host, String rpc_port, String rpc_user, String rpc_password) {
        URL = rpc_host + ":" + rpc_port;

        String cred = Base64.encodeBase64String((rpc_user + ":" + rpc_password).getBytes());
        Map<String, String> headers = new HashMap<>(1);
        headers.put("Authorization", "Basic " + cred);
        try {
            this.mClient = new JsonRpcHttpClient(new URL(URL), headers);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    /***
     * 网络请求和数据处理
     * @param: [method, var] 方法&参数
     * @return: java.lang.String 结果
    //     **/
    public String engine(@NotNull String method, Object... var) {
        return engine(method, String.class, var);
    }

    public <T> T engine(@NotNull String method, Class<T> clazz, Object... var) {

        try {
            return mClient.invoke(method, var, clazz);
        } catch (Throwable throwable) {
            String message = throwable.getMessage();
            Throwable cause = throwable.getCause();
            log.error(cause == null ? "error cause=null" : "error cause=" + cause.getMessage());
            log.error(throwable == null ? "error message=null" : "error message=" + throwable.getMessage());
            try {
                BaseRPCresponse res = JSON.parseObject(message, BaseRPCresponse.class);
                BaseRPCresponse.ErrorBean error = res.getError();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
